/*
 * main.cpp
 *
 *  Created on: May 7, 2010
 *      Author: Mario Rodriguez Huizar
 */

#include "ADCBoard.h"

#define BASE_ADDRESS_16		0x21E00000
#define BASE_ADDRESS_8		0x11E00000
#define MAX_QUEUE_SIZE		50
#define MAX_CHANNEL			1
#define SAMPLE_RATE_HZ		200

int main(){
	int8_t returnStatus = 0;
	uint8_t maxChanNorm = 0;

	if(MAX_CHANNEL%2==0){
		maxChanNorm = MAX_CHANNEL+1;
	} else {
		maxChanNorm = MAX_CHANNEL;
	}

	ADCQueueManager myQueueManager(MAX_QUEUE_SIZE, MAX_ADC_CHANNELS);
	ADCBoard myADCBoard(BASE_ADDRESS_16, BASE_ADDRESS_8, 1);

	returnStatus = myADCBoard.initADC(&myQueueManager);
	if (returnStatus != 0){
		fprintf(stderr, "Board failed initialization: %d (%s)\n", returnStatus, myADCBoard.tsadclib1624_errors(returnStatus));
		return 1;
	}
	myADCBoard.config(MAX_CHANNEL, SAMPLE_RATE_HZ, ADCRANGE_55S);
	while(true){
		ADCPacket *receivedPacket;   //temporary pointer to read the received data
		int8_t sampleReady;

		sampleReady = myADCBoard.readFifo(); //start collecting data from fifo into buffers
		if(sampleReady == TSADCSTATUS_NODATA){ // no data available
			usleep(50000); //go to sleep, in the meantime the FIFO will start to fill up
		} else if(sampleReady == TSADCSTATUS_DATA){ //there is a sample ready
			for(uint8_t index=0; index<=maxChanNorm; index++){ //get the sample and print it
				receivedPacket=myQueueManager.popADCpacket(index);
				assert(receivedPacket);
				//print packet
				printf("Channel:%d\n",index );
				for(uint16_t lenght=0; lenght < receivedPacket->length; lenght++)
					printf("data: %d\n", receivedPacket->adcData[lenght]);
				//IMPORTANT!!! free the memory
				delete receivedPacket; //If not our program will run out of memory!!!
			}
		} else {
			fprintf(stderr, "ADC error: %d (%s)\n", sampleReady, myADCBoard.tsadclib1624_errors(sampleReady));
		}
	}

	return 0;
}
